/* 
 * File:   Client.cpp
 * Author: pson
 * 
 * Created on May 31, 2011, 10:52 AM
 */

#include "Client.h"
#include "../terrain/Chunk.h"

#include <iostream>
#include <stdlib.h>

using namespace std;

Client::Client() {
    size_buf = 256;
}


Client::~Client() {
}

int Client::load_chunk(istream* in, Chunk* chunk) {
    //Check that the input stream and chunk are valid
    if (!in || !chunk) {
        return -1;
    }
    //create a buffer
    unsigned char buf[size_buf];
    //a state to tell which part of the cell we are receiving.
    int st = TERRAIN;
    int c = 0;
    cout << "STARTING\n";
    
    while(in->good()) {
        in->read(reinterpret_cast<char*>(buf), size_buf);
        int ptr = 0;
        while (ptr < size_buf) {
            if (buf[ptr] == REPEAT) {
                unsigned char t = buf[ptr+1];
                unsigned short n = (buf[ptr+2] << 8) + buf[ptr+3];
                cout << "REPEAT: " << (int)t << " x " << n << "\n";
                for (unsigned short i = 0; i < n; ++i) {
                    chunk->getCell(i+c)->set_terrain(t);
                }
                ptr += 4;
                c += n;
                
            } else if (buf[ptr] == NEXT) {
                cout << "GOING TO NEXT\n";
                c = 0;
                st++;
                ptr++;
            } else if (buf[ptr] == 0) {
                cout << "\nEOF\n";
                ptr = size_buf;
            } else {
                unsigned char t = buf[ptr];
                chunk->getCell(c)->set_terrain(t);
                cout << int(t) << "|";
                c++;
                ptr++;
            }
        }
        
    }
}